package com.glsc.ngateway.opmanage.service.report.excel.listener.regulatory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.fileupload.ImportTemplateRulesDefine;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.regulatory.RegRptNAFMIIScale;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.regulatory.RegRptNAFMIIScaleRepo;
import com.glsc.ngateway.opmanage.service.report.excel.listener.TemplateCheckHandler;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RegRptNAFMIIScaleListener extends AnalysisEventListener<RegRptNAFMIIScale> {

    private static final int BATCH_COUNT = 3000;
    List<RegRptNAFMIIScale> list = new ArrayList<RegRptNAFMIIScale>();

    private List<ImportTemplateRulesDefine> rulesDefineList;
    private RegRptNAFMIIScaleRepo tnafmiiScaleRepo;
    private BigInteger mainId;
    private BigInteger id;

    public RegRptNAFMIIScaleListener() {
    }

    public RegRptNAFMIIScaleListener(RegRptNAFMIIScaleRepo tnafmiiScaleRepo, BigInteger mainId,
                                     List<ImportTemplateRulesDefine> rulesDefineList) {
        this.tnafmiiScaleRepo = tnafmiiScaleRepo;
        this.mainId = mainId;
        this.id = BigInteger.valueOf(1);
        this.rulesDefineList = rulesDefineList.stream().filter(item -> item.getSheetIndex().equals(0)).collect(Collectors.toList());
    }

    @Override
    public void invoke(RegRptNAFMIIScale data, AnalysisContext analysisContext) {
        TemplateCheckHandler.check(analysisContext, rulesDefineList);
        data.setMainId(mainId);
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        if (rowIndex >= 10 && rowIndex <= 15) {
            data.setId(id);
            list.add(data);
            id = id.add(BigInteger.valueOf(1));
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        TemplateCheckHandler.check(context, rulesDefineList);
    }

    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        tnafmiiScaleRepo.saveAll(list);
    }
}
